// ==UserScript==
// @name           Sparkly Comics
// @namespace      http://www.lmnopc.com/greasemonkey/
// @description    Turns Sparkly's posts into comics 
// @include        http://shacknews.com/*
// @include        http://*.shacknews.com/*
// ==/UserScript==

/* 
	05-19-2009
		- Initial release
	05-20-2009
		- Added TroZ's font resizing code.  Sweet!
	05-20-2009 Noon
		- Fixed URL parsing so it deals with links that have newlines in them
	2009-06-10
		- Sparkly Comics
	2009-09-10
		- Fixed my super lazy sentence parsing.  It went from one line to 58.  lol 
	2009-09-19
		- Added support for spoiler tags.  The regular expression may need to be tweaked in the future. 

*/ 

if ((script_enabled('sparkly_comics') == "true") && (location.href.indexOf('laryn.x') != -1))
{

(function() {

    var benchmarkTimer = null;
    var scriptStartTime = getTime();
    function getTime() { benchmarkTimer = new Date(); return benchmarkTimer.getTime(); }


function stripHtml(html) { return String(html).replace(/(<([^>]+)>)/ig, ''); }
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); }

function parsePost(post)
{
	var res = new Array(); 

	// Extract all the links, store them in links[] and replace the link with a %%link%% placeholder in the post 
	var links = new Array(); 
	var regExLink = new RegExp(/<a.*? href=(\"|')(.*?)([\n|\r]*?)(\"|').*?>(.*?)([\n|\r]*?)<\/a>/i);
	do 
	{
		var m = regExLink.exec(post);
		if (m == null) 
		{
			break;
		}
		links.push(m[0]); 
		post = post.replace(regExLink, '%%link%%'); 
	}
	while (1)
	
	var spoilers = new Array(); 
	var regExSpoiler = new RegExp(/<span class="jt_spoiler" onclick="return doSpoiler\( event \);">(|.|\r|\n)*?<\/span>/i); 
	do 
	{
		var m = regExSpoiler.exec(post);
		if (m == null) 
		{
			break;
		}
		spoilers.push(m[0]); 
		post = post.replace(regExSpoiler, '%%spoiler%%'); 
	}
	while (1)

	// Strip HTML from the post 	
	post = stripHtml(post);
	
	// Split paragraphs
	var lines = post.split('\n');
	
	// Get sentences from paragraphs
	for (var i = 0; i < lines.length; i++)
	{
		lines[i] = lines[i].replace('...', '&Ellipsis;'); 

		/*
		var sentences = lines[i].split('.');
		*/

		var sentences = new Array();

		str = lines[i];  
		
		pos = 0; 
		var emergencyExit = 0; 
		do 
		{
		   // Stop looping if we hit 255 attempts - probably stuck in a loop 
		   if (++emergencyExit >= 255) 
			{ 
				alert('emergency exit!');
				break;  
			}

			// Find next punctuation mark 
			pos += str.substr(pos).search(/[!|\.|\?]/); 
		   
		   // If a punctuation mark is found ... 
		   if (pos != -1)
		   {
		   	// Make sure this isn't a decimal place 
		   	if ((str.substr(pos, 1) == '.') && (pos + 1 != str.length))
		   	{
		   		if (str.substr(pos + 1, 1).length > 0)
		   		{
				   	if (String('0123456789').indexOf(str.substr(pos + 1, 1)) != -1)
				   	{
				   		pos++; 
				   		continue; 
				   	}
			   	}
				}		   	
		   	
		      end = str.indexOf(' ', pos); 
		      if (end == -1)
		      {
		      	pos = -1;
					break;
		      }
		      else 
		      {
		      	// Push new sentence 
		         sentences.push(str.substring(0, end));
					
					// Truncate what's been added to sentences from str and reset pos 
		         str = str.substr(end + 1).trim(); 
		         pos = 0;
		      }
		   }
		}
		while ((pos != -1) && (str.length > 0))
		
		// Push the remainder of the line into sentences 
		if (str.length)
		{
			sentences.push(str); 
		}

		// Fix links and ellipsiseseses	
		for (var j = 0; j < sentences.length; j++)
		{
			if (sentences[j].length)
			{
				var tmp = sentences[j];
				tmp = tmp.replace('&Ellipsis;', '...'); 

				// replace %%link%% placeholders with actual links
				while (tmp.indexOf('%%link%%') > -1)
				{
					tmp = tmp.replace(/%%link%%/i, links.shift());
				}
				
				while (tmp.indexOf('%%spoiler%%') > -1)
				{
					tmp = tmp.replace(/%%spoiler%%/i, spoilers.shift()); 
				}

				res.push(tmp);
			}
		}
	}
	return res; 
}



function frame(x, y, width, height, lines)
{
	this.x = x; 
	this.y = y; 
	this.width = width; 
	this.height = height; 
	this.lines = lines;
}

var frames = new Array(
	new frame(5, 5, 234, 92, 7),
	new frame(248, 5, 121, 92, 7), 
	new frame(517, 5, 214, 150, 11), 
	new frame(4, 246, 186, 67, 5), 
	new frame(198, 246, 291, 66, 5), 
	new frame(496, 246, 234, 56, 4)
);


function processPost(id)
{
	var comicId = 'sparklyComic_' + id; 

	// Prevent duplicate comics
	if (document.getElementById(comicId))
	{
		return; 
	}
	
	var item = document.getElementById(id); 
	
	var thePost = getElementByClassName(item, 'div', 'postbody'); 
	
	if (typeof(thePost) == 'undefined')
	{
		return;
	}

	var text = parsePost(thePost.innerHTML); 
	
	// Create Sparkly Comic container
	var div = document.createElement('div');
	div.className = 'sparkly-comic';
	div.id = comicId; 
	div.style.display = 'block';
	div.style.width = '100%';
	div.style.textAlign = 'center';
	div.style.fontSize = '20px';
	div.style.fontWeight = 'bold';
	div.style.lineHeight = '1em';
	div.style.color = '#fff';
	// div.style.position = 'relative';
	div.style.float = 'left'; 
	
	thePost.appendChild(div); 
	
	// Populate frames
	for (var i = 0; i < text.length; i++)
	{	
		var f = document.createElement('div');

		f.className = 'cel';
		
		f.style.cssFloat = 'left'; 
		f.style.display = 'block';
		f.style.width = '240px';
		f.style.height = '351px';
		f.style.margin = '2px';
		
		// Shift the background image based on the contents of the post
		
		lc = text[i].toLowerCase(); 
		
		// YELLING
		if (lc.indexOf('!') != -1)
		{
			f.style.backgroundPosition = '-249px 0'; 
		}
		
		// Let me show you my O face 
		else if (lc.indexOf(':o') != -1)
		{
			f.style.backgroundPosition = '-249px 0'; 
		}
		
		// Sparkly gets mad.  You wouldn't like him when he's mad.   
		else if (lc.indexOf('&gt;:[') != -1)
		{
			f.style.backgroundPosition = '-1004px 0'; 
		}
		
		// Sparkly gets sad.  You wouldn't like him when he's sad.   
		else if ((lc.indexOf(':(') != -1) || (lc.indexOf(':[') != -1))
		{
			f.style.backgroundPosition = '-1258px 0'; 
		}
		
		// Que? 
		else if (lc.indexOf('?') != -1)
		{
			f.style.backgroundPosition = '-747px 0';
		}
		
		// LOL or NWS
		else if ((lc.indexOf('lol') != -1) || (lc.indexOf('nws') != -1))
		{
			f.style.backgroundPosition = '-499px 0';
		}
		
		// wtf? 
		else if (lc.indexOf('wtf') != -1)
		{
			f.style.backgroundPosition = '-747px 0';
		}
		
		
		else if (lc.indexOf(':/') != -1)
		{
			f.style.backgroundPosition = '0';
		}
		
		// end on a smile
		else if (i == (text.length - 1))
		{
			f.style.backgroundPosition = '-499px 0';
		}
		
		// default sparkly
		else 
		{
			f.style.backgroundPosition = '0';
		}
		
		f.style.verticalAlign = 'bottom';
		f.style.overflow = 'hidden'; 
		f.style.lineHeight = '1em';
		f.style.position = 'relative'; 
		
		f1 = document.createElement('span');
		f1.className = 'shadow';
		f1.style.position = 'absolute';
		f1.style.color = '#000';
		f1.style.left = '2px';
		f1.style.right = '0';
		f1.style.bottom = '0';
		f1.innerHTML = text[i];
		f.appendChild(f1); 
		
		f2 = document.createElement('span');
		f2.style.position = 'absolute';
		f2.style.color = '#fff';
		f2.style.left = '0';
		f2.style.right = '2px';
		f2.style.bottom = '2px'; 
		f2.innerHTML = text[i]; 
		f.appendChild(f2);
		
		div.appendChild(f);  
	}
}

	function main() 
	{
		var posts = document.evaluate("//div[contains(@class,'fpauthor_170040')]/..",document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);
		for (var i = 0; i < posts.snapshotLength; i++) 
		{
			processPost(posts.snapshotItem(i).id);
		}
	}

	// Call main() 
	main();

	// Install javascript replacement function 
	if ((typeof(sparkly_show_item_fullpost) == 'undefined') && (typeof(show_item_fullpost) != 'undefined')) 
	{
	   sparkly_show_item_fullpost = show_item_fullpost;
	   show_item_fullpost = function(root_id, article_id, fullpost_element) 
		{
			sparkly_show_item_fullpost(root_id, article_id, fullpost_element);
			
			var id = 'item_' + article_id; 
			
			// Make sure sparkly wrote this post
			if (document.getElementById(id).getElementsByTagName('div')[0].className.indexOf('fpauthor_170040') != -1)
			{
				processPost(id);
			}
	   }
	}
	
	// Install event handler on iframe to call main 
	document.getElementById('dom_iframe').addEventListener('load', function() { setTimeout(main, 100); } , false); 

	// Log execution time 
	GM_log('sparkly_comics.js: ' + (getTime() - scriptStartTime) + 'ms');

})();

}
